<script setup>
import { getUserOrderAPI,cancelOrderAPI } from '@/apis/order'
import { onMounted, ref } from 'vue'
import Cookies from "js-cookie"
import {ElMessage} from "element-plus";
import router from "@/router";
import dayjs from "dayjs";
import { ElMessageBox } from 'element-plus' // 引入确认对话框
// tab列表
// const tabTypes = [
//   { name: 'all', label: '全部订单' },
//   { name: 'unpay', label: '待付款' },
//   { name: 'deliver', label: '待发货' },
//   { name: 'receive', label: '待收货' },
//   { name: 'comment', label: '待评价' },
//   { name: 'complete', label: '已完成' },
//   { name: 'cancel', label: '已取消' }
// ]

const formatPayState = (payState) => {
  return stateMap[payState]?.text || '未知状态'
}

// 使用冻结对象创建枚举（防止意外修改）
const ORDER_STATUS = Object.freeze({
  UNPAY: 1,     // 待付款
  DELIVER: 2,    // 待发货
  RECEIVE: 3,    // 待收货
  COMMENT: 4,    // 待评价
  COMPLETE: 5,   // 已完成
  CANCEL: 0      // 已取消
})

// 完整的状态映射（使用计算属性名）
const stateMap = {
  [ORDER_STATUS.UNPAY]: {
    text: '待付款',
    color: '#e6a23c'
  },
  [ORDER_STATUS.DELIVER]: {
    text: '待发货',
    color: '#409eff'
  },
  [ORDER_STATUS.RECEIVE]: {
    text: '待收货',
    color: '#f56c6c'
  },
  [ORDER_STATUS.COMMENT]: {
    text: '待评价',
    color: '#909399'
  },
  [ORDER_STATUS.COMPLETE]: {
    text: '已完成',
    color: '#67c23a'
  },
  [ORDER_STATUS.CANCEL]: {
    text: '已取消',
    color: '#d9d9d9'
  }
}

// 订单列表
const orderList = ref([])
const total = ref(0)
// const params = ref({
//   memberId: memberId.value,
//   // orderState: 0,
//   page: 1,
//   pageSize: 2
// });

const params = ref({
  memberId: null,
  orderState: 0, // 默认全部订单
  page: 1,
  pageSize: 5     // 建议每页显示5条
})

const getUserOrder = async () => {
  try {
    // 从Cookie获取用户ID
    const memberId = Cookies.get('memberId')
    if (!memberId) {
      // 处理未登录情况
      return router.push('/login')
    }

    const res = await getUserOrderAPI({
      ...params.value,
      memberId // 确保传递正确的用户ID
    })

    // 处理日期格式化
    orderList.value = res.data.list.map(order => ({ // 对应PageInfo的list字段
      ...order,
      createTime: dayjs(order.createTime).format('YYYY-MM-DD HH:mm')
    }))
    console.log(orderList.value);
    total.value = res.data.total // 对应PageInfo的total字段
  } catch (e) {
    ElMessage.error('获取订单失败')
  }
}

onMounted(() => getUserOrder())
// 导航栏切换
const tabChange = (type) => {
  params.value.orderState = type
  getUserOrder()
}
// 页面切换
const pageChange = (page) => {
  params.value.page = page
  getUserOrder()
}
const handleSizeChange = (size) => {
  params.value.pageSize = size
  params.value.page = 1
  getUserOrder()
}
const cancelOrder = async (orderNo) => {
  try {
    // 确认对话框
    await ElMessageBox.confirm(
        '确定要取消该订单吗？',
        '取消订单确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 调用取消订单API
    const res = await cancelOrderAPI(orderNo)

    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      // 重新获取订单列表
      await getUserOrder()
    } else {
      ElMessage.error(res.message || '订单取消失败')
    }
  } catch (error) {
    // 用户点击取消或关闭对话框时，不进行任何操作
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('取消订单失败，请稍后重试')
    }
  }
}
const nowPay=(orderNo,payMoney)=>{
  // const memberId = Cookies.get('memberId');
  console.log("orderNo:"+orderNo);
  console.log("totalPrice:"+payMoney);
  router.push({
    path: '/pay',
    query: {
      orderSn: orderNo,
      totalPrice: payMoney // 确保传递字符串格式金额
    }
  });
  // 更新购物车
  // cartStore.updateCartList();
}
</script>

<template>
<!--  <el-pagination-->
<!--      :total="total"-->
<!--      :current-page="params.page"-->
<!--      :page-size="params.pageSize"-->
<!--      :page-sizes="[5, 10, 20]"-->
<!--      layout="total, sizes, prev, pager, next, jumper"-->
<!--      @size-change="handleSizeChange"-->
<!--      @current-change="pageChange"-->
<!--      background-->
<!--  />-->
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
<!--      <el-tab-pane-->
<!--        v-for="item in tabTypes"-->
<!--        :key="item.name"-->
<!--        :label="item.label"-->
<!--      />-->
      <div class="main-container">
        <div class="holder-container" v-if="orderList.length === 0">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.createTime }}</span>
              <span>订单编号：{{ order.orderNo }}</span>
              <!-- 未付款，倒计时时间还有 -->
              <span class="down-time" v-if="order.orderState === 1">
                <i class="iconfont icon-down-time"></i>
                <b>付款截止: {{ order.countdown }}</b>
              </span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.items" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.picture" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.name }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.attrsText }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                    <div class="count">x{{ item.count }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p :style="{ color: stateMap[order.statusName]?.color }">
                  {{ formatPayState(order.statusName) }}
                </p>
<!--                <p>{{ fomartPayState(order.orderState) }}</p>-->
                <p v-if="order.statusName === 3">
                  <a href="javascript:;" class="green">查看物流</a>
                </p>
                <p v-if="order.statusName === 4">
                  <a href="javascript:;" class="green">评价商品</a>
                </p>
                <p v-if="order.statusName === 5">
                  <a href="javascript:;" class="green">查看评价</a>
                </p>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.payMoney?.toFixed(2) }}</p>
                <p>（含运费：¥{{ order.postFee?.toFixed(2) }}）</p>
                <p>在线支付</p>
              </div>
              <div class="column action">
                <el-button
                  v-if="order.statusName === 1"
                  type="primary"
                  size="small"
                  @click="nowPay(order.orderNo,order.payMoney)"
                >
                  立即付款
                </el-button>
                <el-button
                  v-if="order.statusName === 3"
                  type="primary"
                  size="small"
                >
                  确认收货
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="router.push(`/order/detail/${order.orderNo}`)">
                  查看详情
                </el-button>
                <p v-if="[1,2, 3, 4].includes(order.statusName)">
                  <a href="javascript:;">再次购买</a>
                </p>
                <p v-if="[3, 4].includes(order.statusName)">
                  <a href="javascript:;">申请售后</a>
                </p>
                <p v-if="order.statusName === 1">
                  <!-- 传递正确的订单编号 -->
                  <a @click="cancelOrder(order.orderNo)" class="cancel-link">取消订单</a>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              :total="total"
              @current-change="pageChange"
              :page-size="params.pageSize"
              background
              layout="prev, pager, next"
            />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>
  <el-pagination
      :total="total"
      :current-page="params.page"
      :page-size="params.pageSize"
      :page-sizes="[5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="pageChange"
      background
  />
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.cancel-link {
  color: #999;
  cursor: pointer;

  &:hover {
    color: #f56c6c;
  }
}
.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      > p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>
